<template>
  <el-drawer v-model="state.showDialog" direction="rtl" destroy-on-close :size="size">
    <template #header="{ titleId, titleClass }">
      <h4 :id="titleId" :class="titleClass">{{ title }}</h4>
      <el-icon v-if="state.isFull" class="el-drawer__btn" @click="state.isFull = !state.isFull"
        title="还原"><ele-CopyDocument /></el-icon>
      <el-icon v-else class="el-drawer__btn" @click="state.isFull = !state.isFull"
        title="最大化"><ele-FullScreen /></el-icon>
    </template>
    <div class="my-flex-column w100 h100">
      <el-card v-show="state.showQuery" class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
        <el-form :inline="true" label-width="auto" @submit.stop.prevent>
          <el-form-item>
            <my-select-input v-model="state.pageInput.dynamicFilter" :filters="state.filters" @search="onQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
            <el-button type="primary" icon="ele-Search" @click="onFilter"> 高级查询 </el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card class="my-fill mt8" shadow="never">
        <div class="my-tools-box mb8 my-flex my-flex-between">
          <div>
            <el-button v-auth="'api:industry:production-line:add'" type="primary" icon="ele-Plus" @click="onAdd">
              新增
            </el-button>
          </div>
          <div>
            <el-tooltip effect="dark" :content="state.showQuery ? '隐藏查询' : '显示查询'" placement="top">
              <el-button :icon="state.showQuery ? 'ele-ArrowUp' : 'ele-ArrowDown'" circle
                @click="state.showQuery = !state.showQuery" />
            </el-tooltip>
          </div>
        </div>

        <el-table ref="tableRef" v-loading="state.loading" :data="state.plcOffsetListData" @sort-change="onSortChange"
          row-key="id" @selection-change="handleSelectionChange" border>
          <el-table-column type="selection" :selectable="selectable" :reserve-selection="true" />
          <el-table-column prop="byteOffset" label="偏移" width="80" sortable="custom" show-overflow-tooltip
            align="center" />
          <el-table-column prop="dataType" label="类型" width="95" show-overflow-tooltip align="center">
            <template #default="{ row }">
              <el-tag>{{ convertPLCDataTypeToLabel(row.dataType) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" width="80" align="center" sortable="custom" show-overflow-tooltip />
          <el-table-column prop="description" label="描述" width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="140" header-align="center" align="center" fixed="right">
            <template #default="{ row }">
              <el-button v-auth="'api:industry:production-line:update'" icon="ele-EditPen" size="small" text
                type="primary" @click="onEdit(row)">编辑</el-button>
              <my-dropdown-more>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="onDelete(row)">删除偏移量</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </my-dropdown-more>
            </template>
          </el-table-column>
        </el-table>
        <div class="my-flex my-flex-end" style="margin-top: 10px">
          <el-pagination v-model:currentPage="state.pageInput.currentPage" v-model:page-size="state.pageInput.pageSize"
            :total="state.total" :page-sizes="[10, 20, 50, 100]" small background @size-change="onSizeChange"
            @current-change="onCurrentChange" layout="total, sizes, prev, pager, next, jumper" />
        </div>
      </el-card>
      <MyFilterDialog ref="myFilterDialogRef" :fields="state.filters" @sure="onFilterSure"></MyFilterDialog>
      <PlcOffsetForm ref="plcOffsetFormRef" :title="state.plcOffsetFormTitle"></PlcOffsetForm>
    </div>
    <template #footer>
      <div style="flex: auto; padding: 20px !important">
        <el-button @click="onCancel" size="default">取 消</el-button>
        <el-button type="primary" @click="onSure" size="default">确 定</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script lang="ts" setup name="industry/plc-offset">
import { ref, reactive, onMounted, getCurrentInstance, onBeforeMount, defineAsyncComponent, computed, toRaw } from 'vue'
import { PLCOffsetGetPageOutput, PageInputPLCOffsetGetPageInput, PLCOffsetGetOutput, PLCDataTypeEnum, SortInput, BlockOffsetBlockIdInput } from '/@/api/industry/data-contracts'
import { BlockOffsetApi } from '/@/api/industry/BlockOffset'
import { PlcOffsetApi } from '/@/api/industry/PlcOffset'
import eventBus from '/@/utils/mitt'
import { auth } from '/@/utils/authFunction'
import { ElTable } from 'element-plus'
import { number } from 'echarts'

const tableRef = ref<InstanceType<typeof ElTable>>()
const { proxy } = getCurrentInstance() as any
const MyFilterDialog = defineAsyncComponent(() => import('/@/components/my-filter/dialog.vue'))
const MySelectInput = defineAsyncComponent(() => import('/@/components/my-select-input/index.vue'))
const MyDropdownMore = defineAsyncComponent(() => import('/@/components/my-dropdown-more/index.vue'))
const PlcOffsetForm = defineAsyncComponent(() => import('./compoents/plc-offset-form.vue'))

defineProps({
  title: {
    type: String,
    default: 'PLC偏移量',
  },
})
const getSortList = (data: { prop: string; order: any }) => {
  return [
    {
      propName: data.prop,
      order: data.order === 'ascending' ? 0 : data.order === 'descending' ? 1 : undefined,
    },
  ] as [SortInput]
}
const myFilterDialogRef = ref();
const plcOffsetFormRef = ref();
const selectedRows = ref<PLCOffsetGetPageOutput[]>([]);
const plcDataType = {
  0: 'BOOL',
  1: 'BYTE',
  2: 'WORD',
  3: 'DWORD',
  4: 'INT',
  5: 'DINT',
  6: 'REAL',
  7: 'LREAL',
  8: 'STRING'
} as const
const convertPLCDataTypeToLabel = (dataType: PLCDataTypeEnum) => plcDataType[dataType] as string;
const defalutSort = { prop: 'sort', order: 'ascending' }

const state = reactive({
  plcOffsetFormTitle: '',
  loading: false,
  showDialog: false,
  sureLoading: false,
  showQuery: true,
  isFull: false,
  total: 0,
  isMobile: document.body.clientWidth < 1200,
  offsetIds: [] as Array<number>,
  blockIdOfBlock: {
    blockId: 0
  } as BlockOffsetBlockIdInput,
  pageInput: {
    currentPage: 1,
    pageSize: 20,
    sortList: getSortList(defalutSort),
    filter: {
    },
    dynamicFilter: {},
  } as PageInputPLCOffsetGetPageInput,
  plcOffsetListData: [] as Array<PLCOffsetGetPageOutput>,
  filters: [
    {
      field: 'byteOffset',
      operator: 'Contains',
      description: '偏移',
      componentName: 'el-input',
      defaultSelect: true,
    },
    {
      field: 'description',
      operator: 'Contains',
      description: '描述',
      componentName: 'el-input',
      defaultSelect: false,
    }
  ] as Array<DynamicFilterInfo>,
})

onMounted(async () => {
  eventBus.off('refreshPLCOffset')
  eventBus.on('refreshPLCOffset', async () => {
    onQuery()
  })
})
onBeforeMount(() => {
  eventBus.off('refreshPLCOffset')
})

const getOffsetId = async () => {
  const res = await new BlockOffsetApi().getOffsetIds(state.blockIdOfBlock).catch(() => {
  })
  state.offsetIds = res?.data ?? [];
}
const selectable = (row: PLCOffsetGetPageOutput) => !state.offsetIds.includes(row.id)

const handleSelectionChange = (row: PLCOffsetGetPageOutput[]) => {
  selectedRows.value = row
}
//查询分页
const onQuery = async () => {
  state.loading = true
  await getOffsetId();
  const res = await new PlcOffsetApi().getPage(state.pageInput).catch(() => {
    state.loading = false
  })
  state.plcOffsetListData = res?.data?.list ?? []
  state.total = res?.data?.total ?? 0
  state.loading = false
}
//高级查询
const onFilter = () => {
  myFilterDialogRef.value.open()
}

//新增
const onAdd = () => {
  state.plcOffsetFormTitle = '新增偏移量信息'
  plcOffsetFormRef.value.open()
}

//修改
const onEdit = (row: PLCOffsetGetOutput) => {
  state.plcOffsetFormTitle = '编辑偏移量信息'
  plcOffsetFormRef.value.open(row)
}

//删除
const onDelete = (row: PLCOffsetGetOutput) => {
  proxy.$modal
    .confirmDelete(`确定要删除偏移量为【${row.byteOffset}】?`)
    .then(async () => {
      await new PlcOffsetApi().softDelete({ id: row.id }, { loading: true, showSuccessMessage: true })
      onQuery()
    })
    .catch(() => { })
}
const onFilterSure = (dynamicFilter: any) => {
  state.pageInput.dynamicFilter = dynamicFilter
  onQuery()
}

const onSizeChange = (val: number) => {
  state.pageInput.currentPage = 1
  state.pageInput.pageSize = val
  onQuery()
}

const onCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  onQuery()
}
const onSortChange = (data: { column: any; prop: string; order: any }) => {
  state.pageInput.sortList = getSortList(data)
  onQuery()
}
const emits = defineEmits(['sure'])

const size = computed(() => {
  return state.isMobile ? '100%' : state.isFull ? '100%' : '45%'
})

// 打开对话框
const open = (blockId: any) => {
  state.blockIdOfBlock = blockId;
  state.showDialog = true
  onQuery();
}


// 取消
const onCancel = () => {
  state.showDialog = false
}

// 确定
const onSure = () => {
  const selectedRows = tableRef.value?.getSelectionRows() || [];
  // 确保 ID 数组是 number[] 类型，转换为数字
  const selectedIds: number[] = selectedRows.map((row: any) => {
    // 将 row.id 转换为数字类型，如果 row.id 不是有效的数字，可以设置默认值（例如 0 或者 null）
    return Number(row.id);  // 转换为数字
  });
  emits('sure', selectedIds)
  state.showDialog = false
}

defineExpose({
  open,
})
</script>

<style scoped lang="scss">
.el-alert {
  border-width: 0px !important;
  margin-left: 110px;
  margin-top: 10px;
}

.el-drawer__btn {
  cursor: pointer;
  margin-right: 8px;

  &:hover {
    color: var(--el-color-primary);
  }
}
</style>